<template>
  <!-- 异常趋势分析 - 年报 -->
  <a-spin :spinning="loading">
    <div class="AbnormalTrend">
      <div class="titleBar">
        <div class="title">
          异常趋势分析 - 年报
          <div class="dateRange">
            <a-date-picker
              v-model:value="timeData"
              picker="year"
              value-format="YYYY"
              format="YYYY"
              :disabled-date="disabledDate"
              style="margin-right: 8px"
              size="small"
            />
            <a-button
              size="small"
              type="primary"
              class="queryBtn"
              @click="outageDashboardData"
              >查询</a-button
            >
            <a-button size="small" type="link" @click="handleReset"
              >重置</a-button
            >
          </div>
        </div>
      </div>
      <div class="content">
        <div class="topChart">
          <div class="lineChart">
            <div class="chartTitle">
              {{
                currentDisplayYear &&
                currentDisplayYear !== "0" &&
                currentDisplayYear !== 0
                  ? `${currentDisplayYear}-年${
                      props.pageType === "Unplanned" ? "非计划" : "计划"
                    }故障趋势图`
                  : "请选择年份查看数据"
              }}
            </div>
            <div ref="lineChartRef" class="chartContainer"></div>
          </div>
        </div>
        <div class="bottomChart">
          <div class="chartTitle">
            {{ getBottomChartTitle() }}
          </div>
          <div ref="horizontalBarChartRef" class="chartContainer"></div>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup>

import * as echarts from "echarts";
import dayjs from "dayjs";

const timeData = ref(dayjs().subtract(1, "year").format("YYYY"));
const $api = inject("$api");
const props = defineProps({
  pageType: {
    type: String,
  },
});
const disabledDate = (current) => {
  return current && current.isAfter(dayjs().startOf("year").subtract(0, "day"));
};

const chartData = ref([]);
const selectedMonthData = ref(null);
// 添加当前显示的年份（用于标题显示）
const currentDisplayYear = ref(dayjs().subtract(1, "year").format("YYYY"));

const horizontalBarChartRef = ref(null);
const lineChartRef = ref(null);

let horizontalBarChart = null;
let lineChart = null;

const getBottomChartTitle = () => {
  if (
    !currentDisplayYear.value ||
    currentDisplayYear.value === "0" ||
    currentDisplayYear.value === 0
  ) {
    return "请选择年份查看数据";
  }

  if (selectedMonthData.value && selectedMonthData.value.month !== "0") {
    return `${currentDisplayYear.value}-${selectedMonthData.value.month}各电站${
      props.pageType === "Unplanned" ? "非计划" : "计划"
    }故障次数`;
  }

  return `${currentDisplayYear.value}-各电站${
    props.pageType === "Unplanned" ? "非计划" : "计划"
  }故障次数`;
};

const initHorizontalBarChart = () => {
  if (!horizontalBarChartRef.value) return;

  if (horizontalBarChart) {
    horizontalBarChart.dispose();
  }

  horizontalBarChart = echarts.init(horizontalBarChartRef.value);

  let stationNames = [];
  let values = [];

  if (selectedMonthData.value && selectedMonthData.value.stationMonthCount) {
    const stationData = selectedMonthData.value.stationMonthCount;
    const stationArray = Object.entries(stationData).map(
      ([stationName, count]) => ({
        stationName,
        count: count || 0,
      })
    );
    stationNames = stationArray.map((item) => item.stationName || "-");
    values = stationArray.map((item) => item.count);
  } else {
    stationNames = [];
    values = [];
  }
  // 检查数据是否存在
  if (values.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    horizontalBarChart.setOption(option);
    return;
  }
  const maxValue = Math.max(...values);
  if (maxValue <= 1) {
    // 数据范围0-1时，只显示0和1
    
  }
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    grid: {
      top: "12",
      left: "3%",
      right: "3%",
      bottom: "30",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        // show: false,
        alignWithLabel: true,
      },
      axisLabel: {
        // show: false,
        color: "#94a3b8",
        fontSize: 12,
        interval: 0,
        // rotate: 45,
        // formatter: function (params) {
        //   // 四个字后换行
        //   return params
        //     .split("")
        //     .map((char, index) => {
        //       if ((index + 1) % 4 === 0) {
        //         return char + "\n";
        //       }
        //       return char;
        //     })
        //     .join("");
        // },
      },
      data: stationNames,
    },
    yAxis: {
      type: "value",
      min: 0,
      splitNumber: 3,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        formatter: function (value) {
          return Math.floor(value); // 确保显示整数
        },
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    series: [
      {
        name: "故障次数",
        type: "bar",
        barWidth: 25,
        barGap: 10,
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#00E5FF" },
            { offset: 1, color: "#0077FF" },
          ]),
          borderRadius: [8, 8, 0, 0],
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(51, 65, 85, 0.4)",
          borderRadius: [8, 8, 0, 0],
        },
      },
    ],
    dataZoom: [
      {
        type: "slider",
        show: true,
        xAxisIndex: [0, 1],
        start: 0,
        endValue: window.innerWidth > 1500 ? 15 : 12,
        height: 10,
        bottom: "10",
      },
    ],
  };

  horizontalBarChart.setOption(option);
};

const initLineChart = () => {
  if (!lineChartRef.value) return;

  if (lineChart) {
    lineChart.dispose();
  }
  lineChart = echarts.init(lineChartRef.value);
  const chartDataWithoutSum = chartData.value.filter(
    (item) => item.month !== "0"
  );
  const months = chartDataWithoutSum.map((item) => `${item.month}`);
  const values = chartDataWithoutSum.map((item) => item.monthCount);
  // 检查数据是否存在
  if (chartDataWithoutSum.length === 0 || values.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    lineChart.setOption(option);
    return;
  }
  const finalMonths = months;
  const finalValues = values;
  // 添加一个变量跟踪当前选中的点
  let currentSelectedIndex = -1;
  const option = {
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    grid: {
      left: "3%",
      right: "3%",
      bottom: "5%",
      top: "20",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: true,
      data: finalMonths,
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
    },
    yAxis: {
      type: "value",
      min: 0,
      axisLine: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      splitLine: {
        lineStyle: {
          color: "#334155",
          type: "dotted",
        },
      },
    },
    series: [
      {
        name: "故障次数",
        type: "line",
        smooth: false,
        triggerEvent: true,
        itemStyle: {
          color: (params) => {
            // 选中高亮
            if (params.dataIndex === currentSelectedIndex) {
              return "#FF9F43";
            }
            // 默认颜色
            return new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: "#00E5FF" },
              { offset: 1, color: "#0077FF" },
            ]);
          },
          borderColor: (params) => {
            if (params.dataIndex === currentSelectedIndex) {
              return "#fff";
            }
            return "transparent";
          },
          borderWidth: (params) => {
            return params.dataIndex === currentSelectedIndex ? 2 : 0;
          },
          // 选中点放大显示
          symbolSize: (value, params) => {
            return params.dataIndex === currentSelectedIndex ? 10 : 4;
          },
        },
        lineStyle: {
          width: 2,
        },
        emphasis: {
          focus: "series",
          itemStyle: {
            color: "#2563eb",
            borderColor: "#fff",
            borderWidth: 1,
            opacity: 1,
            symbol: "circle",
            symbolSize: 8,
          },
          lineStyle: {
            width: 3,
          },
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(59, 130, 246, 0.5)",
            },
            {
              offset: 1,
              color: "rgba(59, 130, 246, 0.05)",
            },
          ]),
        },
        data: finalValues,
      },
    ],
  };

  lineChart.setOption(option);

  if (lineChart.getZr()) {
    lineChart.getZr().on("click", function (event) {
      const pixelPoint = [event.offsetX, event.offsetY];
      if (lineChart.containPixel("grid", pixelPoint)) {
        const pointInGrid = lineChart.convertFromPixel(
          { seriesIndex: 0 },
          pixelPoint
        );
        if (pointInGrid) {
          const dataIndex = Math.round(pointInGrid[0]);
          const xAxisData = option.xAxis.data;
          if (dataIndex >= 0 && dataIndex < xAxisData.length) {
            currentSelectedIndex = dataIndex;
            if (chartData.value && chartData.value[dataIndex]) {
              selectedMonthData.value = chartData.value[dataIndex];
              initHorizontalBarChart();
            }
            // 更新图表(这里只是为了触发更改颜色)
            lineChart.setOption({
              series: [
                {
                  name: "故障次数",
                },
              ],
            });
          }
        }
      }
    });
  }
};
const handleReset = async () => {
  timeData.value = dayjs().subtract(1, "year").format("YYYY");
  selectedMonthData.value = null;
  await outageDashboardData();
  initHorizontalBarChart();
  initLineChart();
};

const handleResize = () => {
  horizontalBarChart && horizontalBarChart.resize();
  lineChart && lineChart.resize();
};
const loading = ref(false);
const outageDashboardData = async () => {
  currentDisplayYear.value = timeData.value;
  const params = {
    planShutdown: props.pageType === "Unplanned" ? 0 : 1,
    dashboardYear: timeData.value,
    dashboardType: "3", // 1：故障类别分析 2：故障归属分析 3：异常趋势分析-年报 4：异常趋势分析-月报
  };
  loading.value = true;
  const res = await $api.faultDealDashboard(3, params);
  loading.value = false;
  if (
    res.code === 0 &&
    res.data?.faultDealAnalyzeYearDtoList &&
    Array.isArray(res.data.faultDealAnalyzeYearDtoList)
  ) {
    chartData.value = res.data.faultDealAnalyzeYearDtoList;
    // 如果没有选中的月份数据，选择month=0的数据
    if (!selectedMonthData.value) {
      const monthZeroData = chartData.value.find((item) => item.month === "0");
      if (monthZeroData) {
        selectedMonthData.value = monthZeroData;
      }
    }
  } else {
    chartData.value = [];
    selectedMonthData.value = null;
  }
  await nextTick();
  initHorizontalBarChart();
  initLineChart();
};
onMounted(async () => {
  await outageDashboardData();
  await nextTick();
  initHorizontalBarChart();
  initLineChart();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  horizontalBarChart && horizontalBarChart.dispose();
  lineChart && lineChart.dispose();
});
</script>

<style scoped lang="less">
.AbnormalTrend {
  flex: 1;
  min-width: 0;
  height: 540px;
  width: 100%;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .timeSelect {
    padding: 0 8px;
    width: 140px;
  }

  .content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 5px;
    overflow: hidden;

    .topChart {
      width: 100%;
      height: 180px;
      display: flex;
      flex-direction: column;
      gap: 10px;

      .lineChart {
        flex: 1;
        min-height: 0;

        .chartTitle {
          text-align: center;
          font-size: 14px;
          font-weight: bold;
          color: #e2e8f0;
          padding-top: 10px;
        }

        .chartContainer {
          width: 100%;
          height: 100%;
        }
      }
    }

    .bottomChart {
      width: 100%;
      height: 255px;
      min-width: 0;
      margin-top: 15px;
      .chartTitle {
        text-align: center;
        font-size: 14px;
        font-weight: bold;
        color: #e2e8f0;
        padding-top: 15px;
      }

      .chartContainer {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
